package com.robot.member.service;

import java.util.ArrayList;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import com.alibaba.fastjson.JSON;
import com.robot.member.client.AgentClient;
import com.robot.member.pojo.AgentApply;
import com.robot.member.pojo.MerchantApply;
import com.robot.member.pojo.client.Agent;
import com.robot.member.pojo.client.Store;
import entity.Status;
import entity.StatusCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import util.BinaryUtil;
import util.CheckUtil;
import util.IdWorker;

import com.robot.member.dao.AgentApplyDao;
import util.UpdateUtil;

/**
 * 代理商入驻申请agent_apply服务层
 *
 * @author wuyunbin
 */
@Service
public class AgentApplyService {
    @Autowired
    private AgentApplyDao agentApplyDao;

    @Autowired
    private AgentClient agentClient;

    @Autowired
    private IdWorker idWorker;
    @Autowired
    private CheckUtil checkUtil;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 查询全部列表
     *
     * @return
     */
    public List<AgentApply> findAll() {
        return agentApplyDao.findAll();
    }


    /**
     * 条件查询+分页
     *
     * @param whereMap
     * @param page
     * @param size
     * @return
     */
    public Page<AgentApply> findSearch(Map whereMap, int page, int size) {
        Specification<AgentApply> specification = createSpecification(whereMap);
        PageRequest pageRequest = PageRequest.of(page - 1, size);
        return agentApplyDao.findAll(specification, pageRequest);
    }

    /**
     * 通过phone查询agent_apply列表
     *
     * @param phone
     * @return
     */
    public List<AgentApply> findAllByPhone(String phone) {
        return agentApplyDao.findAllByPhone(phone);
    }


    /**
     * 条件查询
     *
     * @param whereMap
     * @return
     */
    public List<AgentApply> findSearch(Map whereMap) {
        Specification<AgentApply> specification = createSpecification(whereMap);
        return agentApplyDao.findAll(specification);
    }

    /**
     * 根据ID查询实体
     *
     * @param id
     * @return
     */
    public AgentApply findById(String id) {
        return agentApplyDao.findById(id).orElse(null);
    }

    /**
     * 增加
     *
     * @param apply
     */
    public void add(AgentApply apply) {
        //雪花分布式ID生成器
        apply.setId(BinaryUtil.decimal2Base62(idWorker.nextId()));
        apply.setStatus("0");
        LocalDateTime now = LocalDateTime.now();
        apply.setCreatedAt(now);
        apply.setUpdatedAt(now);
        agentApplyDao.save(apply);
    }

    /**
     * 修改
     *
     * @param apply
     */
    public void update(AgentApply apply) {
        AgentApply agentApplyInDb = findById(apply.getId());
        UpdateUtil.copyNonNullProperties(apply, agentApplyInDb);
        apply.setUpdatedAt(LocalDateTime.now());
        agentApplyDao.save(agentApplyInDb);
    }

    /**
     * 删除
     *
     * @param id
     */
    public void deleteById(String id) {
        agentApplyDao.deleteById(id);
    }

    /**
     * 检查实体类是否存在
     *
     * @param agentApplyInDb
     * @return
     */
    public String checkPojo(AgentApply agentApplyInDb) {
        if (agentApplyInDb == null) {
            return ("代理申请单不存在");
        }
        if (agentApplyInDb.getDeletedAt() != null) {
            return ("代理申请单已删除");
        }
        return "";
    }

    /**
     * 动态条件构建
     *
     * @param searchMap
     * @return
     */
    private Specification<AgentApply> createSpecification(Map searchMap) {
        return new Specification<AgentApply>() {
            @Override
            public Predicate toPredicate(Root<AgentApply> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicateList = new ArrayList<Predicate>();
                // 申请单Id
                String id = "id";
                if (searchMap.get(id) != null && !"".equals(searchMap.get(id))) {
                    predicateList.add(cb.like(root.get(id).as(String.class), "%" + (String) searchMap.get(id) + "%"));
                }
                // 会员id
                String memberId = "memberId";
                if (searchMap.get(memberId) != null && !"".equals(searchMap.get(memberId))) {
                    predicateList.add(cb.like(root.get(memberId).as(String.class), "%" + (String) searchMap.get(memberId) + "%"));
                }
                // 联系电话
                String phone = "phone";
                if (searchMap.get(phone) != null && !"".equals(searchMap.get(phone))) {
                    predicateList.add(cb.like(root.get(phone).as(String.class), "%" + (String) searchMap.get(phone) + "%"));
                }
                // 联系人名称
                String contact = "contact";
                if (searchMap.get(contact) != null && !"".equals(searchMap.get(contact))) {
                    predicateList.add(cb.like(root.get(contact).as(String.class), "%" + (String) searchMap.get(contact) + "%"));
                }
                // 省份
                String province = "province";
                if (searchMap.get(province) != null && !"".equals(searchMap.get(province))) {
                    predicateList.add(cb.like(root.get(province).as(String.class), "%" + (String) searchMap.get(province) + "%"));
                }
                // 省份id
                String provinceId = "provinceId";
                if (searchMap.get(provinceId) != null && !"".equals(searchMap.get(provinceId))) {
                    predicateList.add(cb.like(root.get(provinceId).as(String.class), "%" + (String) searchMap.get(provinceId) + "%"));
                }
                // 城市
                String city = "city";
                if (searchMap.get(city) != null && !"".equals(searchMap.get(city))) {
                    predicateList.add(cb.like(root.get(city).as(String.class), "%" + (String) searchMap.get(city) + "%"));
                }
                // 城市id
                String cityId = "cityId";
                if (searchMap.get(cityId) != null && !"".equals(searchMap.get(cityId))) {
                    predicateList.add(cb.like(root.get(cityId).as(String.class), "%" + (String) searchMap.get(cityId) + "%"));
                }
                // 区县
                String area = "area";
                if (searchMap.get(area) != null && !"".equals(searchMap.get(area))) {
                    predicateList.add(cb.like(root.get(area).as(String.class), "%" + (String) searchMap.get(area) + "%"));
                }
                // 区县id
                String areaId = "areaId";
                if (searchMap.get(areaId) != null && !"".equals(searchMap.get(areaId))) {
                    predicateList.add(cb.like(root.get(areaId).as(String.class), "%" + (String) searchMap.get(areaId) + "%"));
                }
                // 0-等待审核 1-预审通过 2-预审失败
                String status = "status";
                if (searchMap.get(status) != null && !"".equals(searchMap.get(status))) {
                    predicateList.add(cb.like(root.get(status).as(String.class), "%" + (String) searchMap.get(status) + "%"));
                }
                // 备注
                String remark = "remark";
                if (searchMap.get(remark) != null && !"".equals(searchMap.get(remark))) {
                    predicateList.add(cb.like(root.get(remark).as(String.class), "%" + (String) searchMap.get(remark) + "%"));
                }
                //剔除软删除数据
                String deletedAt = "deletedAt";
                predicateList.add(cb.equal(root.get(deletedAt), cb.nullLiteral(LocalDateTime.class)));

                return cb.and(predicateList.toArray(new Predicate[predicateList.size()]));
            }
        };
    }

    /**
     * 判断手机号
     *
     * @param phone
     * @return
     */
    public Status checkPhoneUsed(String phone, String memberId) {
        if (!checkUtil.checkPhone(phone)) {
            return StatusCode.ERROR_INVALID_PHONE;
        }
        //判断agent是否存在
        Agent agentInDb = JSON.parseObject(agentClient.thirdFindAgentByPhone(phone), Agent.class);
        logger.info("agentInDb=" + agentInDb);
        if (agentInDb != null) {
            return StatusCode.ERROR_DUPLICATE_PHONE;
        }
        //判断手机号是否已被其他会员申请入驻使用
        List<AgentApply> agentApplyList = findAllByPhone(phone);
        if (agentApplyList.size() != 0) {
            return StatusCode.ERROR_DUPLICATE_PHONE;
        }
        return null;
    }

    /**
     * 通过memberId查询最新agent_apply详情
     *
     * @param memberId
     * @return
     */
    public AgentApply findTopByMemberIdOrderByCreatedAtDesc(String memberId) {
        return agentApplyDao.findTopByMemberIdOrderByCreatedAtDesc(memberId);
    }

    /**
     * 通过id和memberId查询最新agent_apply详情
     *
     * @param id
     * @param memberId
     * @return
     */
    public AgentApply findByIdAndMemberIdAndDeletedAtIsNull(String id, String memberId) {
        return agentApplyDao.findByIdAndMemberIdAndDeletedAtIsNull(id, memberId);
    }
}
